package com.xianshijian.oauth.userinfo.task;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.xianshijian.oauth.userinfo.dao.ClientUserDao;
import com.xianshijian.oauth.userinfo.entity.ClientUser;



/**
 * 清除过期的access_toke
 * 
 * @author lzj
 *
 */
@Component  
public class ClearExpireAccessTokenTask {
	
	@Autowired
	private ClientUserDao clientUserDao;
	
	
	/**
	 * 删除数据库中已过期的缓存
	 * 
	 * 规则：每20分钟跑一次，access_token的过期时间为2天，查询数据库中2天内的记录，删除缓存中的过期数据并删除数据库中的过期数据
	 */
	@Scheduled(cron = "* */20 * * * *")  
    void clearExpireAccessToken(){  
		//获取前2天的时间戳   
        Calendar calendar = Calendar.getInstance(); 
		calendar.add(Calendar.DAY_OF_MONTH, -2);  
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmssSSS"); 
		Long twoAfterTimestamp = Long.parseLong(sdf.format(calendar.getTime()));

        List<ClientUser> clientUserList = clientUserDao.findByCreateTime(twoAfterTimestamp);   
        if(clientUserList.size()>0 && clientUserList!=null){
//	        for(ClientUser clientUser : clientUserList){
//	    		client.del(UserCacheKey.OAUTH_USER_BEAN_CACHE + clientUser.getAccessToken());        	
//	        }
	        clientUserDao.deleteInBatch(clientUserList);
        }
    }  
}
